<template>
  <div class="dialog">
    <a-modal class="l-max-modal tech-dialog-cusha" :visible.sync="Dialog" @cancel="closeDialog" :footer="null">
      <div class="header" slot="title">
        <div class="today">
          <img src="~@/assets/img/time.png" width="22" />
          <span>{{ today }}</span>
        </div>
      </div>
      <div class="main">
        <a-radio-group v-model="tableToggle" @change="changeTab">
          <a-radio-button value="车间">车间</a-radio-button>
          <!-- <a-radio-button value="用工">用工</a-radio-button>
          <a-radio-button value="明细">明细</a-radio-button>
          <a-radio-button value="耗电日报">耗电日报</a-radio-button>
          <a-radio-button value="耗电月报">耗电月报</a-radio-button> -->
          <!-- <a-radio-button value="日报">日报</a-radio-button>
          <a-radio-button value="周报">周报</a-radio-button>
          <a-radio-button value="月报">月报</a-radio-button> -->
        </a-radio-group>
        <Legend :status="status" v-show="tableToggle !== '明细'">
          <div class="xiaolv"></div>
        </Legend>
      </div>
      <div class="content" id="CushaSvg" v-show="tableToggle === '车间' || tableToggle === '用工'">
        <!-- 粗纱2 -->
        <CuSha :inline="true" />
      </div>
      <div class="table">
        <a-row
          type="flex"
          justify="space-between"
          v-show="tableToggle === '车间' || tableToggle === '用工' || tableToggle === '明细'"
        >
          <div class="bc-title">{{ workshopData.shiftSpunYarnTxt }}</div>
          <div v-show="tableToggle !== '明细'" class="enlarge" @click="openEnlargeDialog">
            <a-icon type="fullscreen" />
          </div>
        </a-row>
        <!--车间-->
        <WorkshopTable
          v-show="tableToggle == '车间'"
          devName="粗纱"
          :tableData="tableData"
          :loading="loading"
          :scrollY="scrollY"
        />

        <!--用工-->
        <div v-show="tableToggle == '用工'">
          <WorkTable
            v-show="worker == 'detail'"
            devName="粗纱"
            :tableData="tableData1"
            :loading="loading1"
            :scrollY="scrollY"
            @toggle="toggleWorker"
          />
          <WorkAllTable
            v-show="worker == 'sum'"
            devName="粗纱"
            :tableData="tableData3"
            :loading="loading1"
            :scrollY="scrollY"
            @toggle="toggleWorker"
          />
        </div>
        <!--明细-->
        <DetailTable
          v-show="tableToggle == '明细'"
          devName="粗纱"
          :tableData="tableData2"
          :loading="loading2"
          :scrollY="scrollY1"
        />
        <!--耗电日报-->
        <div v-show="tableToggle == '耗电日报'">
          <a-row type="flex" justify="start">
            <div class="yuebao_header_wrap">
              <a-date-picker v-model="electricityDay" placeholder="选择日期" @change="handleElectricityDayDateChange" />
            </div>
            <div class="export_btn" @click="electricityExportXls('耗电日报')">导出</div>
          </a-row>
          <ConsumePowerTableDaily
            devName="粗纱"
            :tableData="electricityDayData.tableData"
            :loading="electricityDayData.loading"
            :scrollY="scrollY1"
          />
          <!-- <a-pagination
            style="margin-top: 15px;"
            size="small"
            :current="electricityDayData.current"
            :pageSize="electricityDayData.size"
            :total="electricityDayData.total"
            @change="handleDayCurrentChange"
          /> -->
        </div>
        <!--耗电月报-->
        <div v-show="tableToggle == '耗电月报'">
          <a-row type="flex" justify="start">
            <div class="yuebao_header_wrap">
              <a-month-picker v-model="electricityMonth" @change="handleElectricityMonthDateChange">
                <a-icon slot="suffixIcon" type="caret-down" />
              </a-month-picker>
            </div>
            <div class="export_btn" @click="electricityExportXls('耗电日报')">导出</div>
          </a-row>
          <ConsumePowerTableMonth
            devName="粗纱"
            :tableData="electricityMonthData.tableData"
            :loading="electricityMonthData.loading"
            :scrollY="scrollY1"
          />
          <!-- <a-pagination
            style="margin-top: 15px;"
            size="small"
            :current="electricityMonthData.current"
            :pageSize="electricityMonthData.size"
            :total="electricityMonthData.total"
            @change="handleMonthCurrentChange"
          /> -->
        </div>
        <!--日报-->
        <div v-show="tableToggle == '日报'">
          <a-row type="flex" justify="start">
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">效率统计：</div>
              <div class="ribao_header_value">{{ RiBaoData.efficiencyActual }}%</div>
            </div>
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">产量统计：</div>
              <div class="ribao_header_value">{{ RiBaoData.yieldActual }}kg</div>
            </div>
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">能耗统计：</div>
              <div class="ribao_header_value">{{ RiBaoData.energyActual }}kw/h</div>
            </div>
            <div class="export_btn" @click="exportxls('日报')">导出</div>
          </a-row>
          <StatisticsTable :tableData="RiBaoData.tableData" :loading="RiBaoData.loading" :scrollY="scrollY1" />
          <a-pagination
            style="margin-top: 15px;"
            size="small"
            :current="RiBaoData.current"
            :pageSize="RiBaoData.size"
            :total="RiBaoData.total"
            @change="handleRiBaoCurrentChange"
          />
        </div>
        <!--周报-->
        <div v-show="tableToggle == '周报'">
          <div v-for="(item, index) in ZhouBaoData" :key="index">
            <a-row type="flex" justify="start">
              <div class="zhoubao_header_riqi">
                <div class="zhoubao_header_riqi_bar"></div>
                <div class="zhoubao_header_riqi_text">
                  {{ item.startTime | dateFormate }}-{{ item.endTime | dateFormate }}
                </div>
              </div>
              <div class="ribao_header_wrap">
                <div class="ribao_header_title">本周效率统计：</div>
                <div class="ribao_header_value">{{ item.efficiencyActual }}%</div>
              </div>
              <div class="ribao_header_wrap">
                <div class="ribao_header_title">本周产量统计：</div>
                <div class="ribao_header_value">{{ item.yieldActual }}kg</div>
              </div>
              <div class="ribao_header_wrap">
                <div class="ribao_header_title">本周能耗统计：</div>
                <div class="ribao_header_value">{{ item.energyActual }}kw/h</div>
              </div>
              <div class="export_btn" @click="exportxls('周报', item.startTime, item.endTime)">导出</div>
            </a-row>
            <StatisticsTable :tableData="item.tableData" :loading="item.loading" :scrollY="scrollY1" />
            <a-pagination
              style="margin-top: 15px;"
              size="small"
              :current="item.current ? item.current : 1"
              :pageSize="item.size ? item.size : 20"
              :total="item.total ? item.total : 0"
              @change="handleZhouBaoCurrentChange($event, index)"
            />
            <div style="width: 100%; height: 25px;"></div>
          </div>
        </div>
        <!--月报-->
        <div v-show="tableToggle == '月报'">
          <a-row type="flex" justify="start">
            <div class="yuebao_header_wrap">
              <a-month-picker class="yuebao_date" v-model="yuebaoMonth" @change="handleYueBaoDateChange">
                <a-icon slot="suffixIcon" type="caret-down" />
              </a-month-picker>
              <a-dropdown :trigger="['click']">
                <a-menu slot="overlay">
                  <a-menu-item v-for="item in workShops" :key="item.value" @click="handleDropDown(item.title)">
                    {{ item.title }}
                  </a-menu-item>
                </a-menu>
                <div class="yuebao_select_box">{{ cjVal }} <a-icon class="yuebao_select_icon" type="down" /></div>
              </a-dropdown>
            </div>
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">当月效率统计：</div>
              <div class="ribao_header_value">{{ YueBaoData.efficiencyActual }}%</div>
            </div>
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">当月产量统计：</div>
              <div class="ribao_header_value">{{ YueBaoData.yieldActual }}kg</div>
            </div>
            <div class="ribao_header_wrap">
              <div class="ribao_header_title">当月能耗统计：</div>
              <div class="ribao_header_value">{{ YueBaoData.energyActual }}kw/h</div>
            </div>
            <div class="export_btn" @click="exportxls('月报')">导出</div>
          </a-row>
          <StatisticsTable :tableData="YueBaoData.tableData" :loading="YueBaoData.loading" :scrollY="scrollY1" />
          <a-pagination
            style="margin-top: 15px;"
            size="small"
            :current="YueBaoData.current"
            :pageSize="YueBaoData.size"
            :total="YueBaoData.total"
            @change="handleYueBaoCurrentChange"
          />
        </div>
      </div>

      <!-- 放大弹框 -->
      <a-modal
        class="l-max-modal echart-dialog"
        :visible.sync="enlargeDialog"
        @cancel="enlargeDialog = false"
        :footer="null"
      >
        <div class="bc-title">{{ workshopData.shiftSpunYarnTxt }}</div>
        <!--车间-->
        <WorkshopTable
          v-show="tableToggle == '车间'"
          devName="粗纱"
          :tableData="tableData"
          :loading="loading"
          :scrollY="scrollY2"
        />
        <div v-show="tableToggle == '用工'">
          <WorkTable
            v-show="worker == 'detail'"
            devName="粗纱"
            :tableData="tableData1"
            :loading="loading1"
            :scrollY="scrollY2"
            @toggle="toggleWorker"
          />
          <WorkAllTable
            v-show="worker == 'sum'"
            devName="粗纱"
            :tableData="tableData3"
            :loading="loading1"
            :scrollY="scrollY2"
            @toggle="toggleWorker"
          />
        </div>
      </a-modal>
    </a-modal>
  </div>
</template>

<script>
import Legend from '@/components/dataScreen/LegendSingle'
import CuSha from '@/components/dataScreen/CuSha'
import { mul, toFixed } from '@/utils/caculate'
import moment from 'moment'
import { urlConfig } from '@/api/urlConfig'
import request from '@/api/request'

import WorkshopTable from '../components/workshop-table/WorkshopTableCusha'
import WorkAllTable from '../components/work-all-table/WorkAllTableCusha'
import WorkTable from '../components/work-table/WorkTableCusha'
import DetailTable from '../components/detail-table/DetailTableCusha'
import ConsumePowerTableDaily from '../components/consume-power-table-daily/ConsumePowerTableDailyCusha'
import ConsumePowerTableMonth from '../components/consume-power-table-month/ConsumePowerTableMonthCusha'
import StatisticsTable from '../components/statistics-table'
import { mapState } from 'vuex'
import { getAction } from '@/api/manage'

export default {
  name: 'cushaDialogTech',
  components: {
    CuSha,
    Legend,
    WorkshopTable,
    WorkAllTable,
    WorkTable,
    WorkAllTable,
    DetailTable,
    ConsumePowerTableDaily,
    ConsumePowerTableMonth,
    StatisticsTable
  },
  data() {
    return {
      url: {
        processDetailsWorkshop: '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetailsWorkshop', // 车间
        processDetailsLabor: '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetailsLabor', //车间用工
        processDetailsLaborEachDevice:
          '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetailsLaborEachDevice', //车间用工明细
        processDetails: '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetails',
        processDetailsConsumptionDay: '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetailsConsumptionDay', // 耗电日报
        processDetailsConsumptionMonth:
          '/ds_device_real_time_status/dsDeviceRealTimeStatus/processDetailsConsumptionMonth', // 耗电月报
        equipmentOperationStatusStatistics:
          '/ds_device_real_time_status/dsDeviceRealTimeStatus/equipmentOperationStatusStatistics' //设备运行状态统计
      },
      Dialog: true,
      bc: '',
      today: '',
      scrollY: 0,
      scrollY1: 0,
      scrollY2: 0,
      tableToggle: '车间',
      tableData: [],
      tableData1: [],
      tableData2: [],
      tableData3: [],
      loading: true,
      loading1: true,
      loading2: true,

      RiBaoData: {
        loading: true,
        current: 1,
        size: 20,
        total: 0
      },
      zhouBaoDate: [],
      ZhouBaoData: {},
      YueBaoData: {
        loading: true,
        current: 1,
        size: 20,
        total: 0
      },
      yuebaoMonth: moment().format('YYYY-MM'),
      yueBaoDate: {
        startTime: moment()
          .startOf('month')
          .format('YYYY-MM-DD 00:00:00'),
        endTime: moment()
          .endOf('month')
          .format('YYYY-MM-DD 23:59:59')
      },
      electricityDayData: {
        loading: true,
        current: 1,
        size: 20,
        total: 0
      },
      electricityMonthData: {
        loading: true,
        current: 1,
        size: 20,
        total: 0
      },
      electricityDay: moment().format('YYYY-MM-DD'),
      electricityDayDate: {
        planTime: moment()
          .startOf('day')
          .format('YYYY-MM-DD')
      },
      electricityMonth: moment().format('YYYY-MM'),
      electricityMonthDate: {
        planTime: moment()
          .startOf('month')
          .format('YYYY-MM')
      },
      cjList: [],
      cjVal: this.$store.state.workshopName,

      worker: 'detail',
      areaArr1: [], //表格行数组
      areaSpan1: 0,
      areaArr2: [], //表格行数组
      areaSpan2: 0,
      areaArr3: [], //表格行数组
      areaSpan3: 0,
      areaArr4: [], //表格行数组
      areaSpan4: 0,
      enlargeDialog: false,
      status: [
        { label: '运行', data: 0 },
        { label: '停止', data: 0 },
        { label: '故障', data: 0 },
        { label: '满纱满桶', data: 0 },
        { label: '通讯失败/停电', data: 0 },
        { label: '计划停台', data: 0 }
      ],
      riBaoFieldName: '',
      riBaoFieldOrder: '',
      yueBaoFieldName: '',
      yueBaoFieldOrder: ''
    }
  },
  computed: {
    ...mapState(['workShops', 'company', 'workshopNo', 'workshopData']),
    workshopName() {
      return this.$store.state.workshopName
    },
    runningStatus() {
      return this.$store.state.runningStatus
    },
    cuShaGroupNewestState() {
      return this.$store.state.cuShaGroupNewestState
    },
    // cuShaWorkerGroupNewestState() {
    //   return this.$store.state.cuShaWorkerGroupNewestState
    // },
    cuShaDetailGroupNewestState() {
      return this.$store.state.cuShaDetailGroupNewestState
    }
    // cuShaWorkerSumGroupNewestState() {
    //   return this.$store.state.cuShaWorkerSumGroupNewestState
    // }
  },
  watch: {
    runningStatus: {
      immediate: true,
      handler(val) {
        if (val && val.code == 1) {
          let { data } = val
          data = data.filter(item => {
            return item.gongxu == '粗纱'
          })
          // for (let i = 0; i < data.length; i++) {
          //   this.status[parseInt(data[i]['stateCode']) - 1]['data'] = data[i]['num']
          // }
        }
      }
    },
    cuShaGroupNewestState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.bc = val.data2 && val.data2.bc
          this.tableData = val.data
          this.loading = false
        }
      }
    },
    // cuShaWorkerGroupNewestState: {
    //   immediate: true,
    //   handler(val) {
    //     let params = ['xiaolv', 'devSn']
    //     if (val) {
    //       let { data } = val
    //       data.map(item => {
    //         params.map(param => {
    //           item[param] = Number(item[param])
    //         })
    //       })
    //       this.clearSort('table1')
    //       this.clearSort('table3')
    //       this.mergeTable(data, '1')
    //       this.mergeTable(data, '3')
    //       this.tableData1 = data
    //       this.loading1 = false
    //     }
    //   }
    // },
    cuShaDetailGroupNewestState: {
      immediate: true,
      handler(val) {
        let params = ['devSn', 'xiaolv', 'llxs', 'iavg', 'dbdh', 'wmdh']
        if (val) {
          let { data } = val
          data.map(item => {
            params.map(param => {
              item[param] = Number(item[param])
            })
          })
          this.tableData2 = data
          this.loading2 = false
        }
      }
    },
    // cuShaWorkerSumGroupNewestState: {
    //   immediate: true,
    //   handler(val) {
    //     let params = ['avg_xiaolv']
    //     if (val) {
    //       let { data } = val
    //       data.map(item => {
    //         params.map(param => {
    //           item[param] = toFixed(item[param])
    //         })
    //       })
    //       this.clearSort('table2')
    //       this.clearSort('table4')
    //       this.mergeTable(data, '2')
    //       this.mergeTable(data, '4')
    //       this.tableData3 = val.data
    //     }
    //   }
    // },
    tableToggle: {
      immediate: true,
      handler(val) {
        switch (val) {
          case '耗电日报':
            this.riBaoFieldName = ''
            this.riBaoFieldOrder = ''
            this.getElectricityDayData(1)
            break
          case '耗电月报':
            this.yueBaoFieldName = ''
            this.yueBaoFieldOrder = ''
            this.getElectricityMonthData(1)
            break
          case '日报':
            this.getRiBaoData(1)
            break
          case '周报':
            this.zhouBaoDate.map(item => {
              this.getZhouBaoData(1, item['firstDay'], item['endDay'])
            })
            break
          case '月报':
            this.getCJ()
            this.getYueBaoData(1)
            break
        }
      }
    }
  },
  created() {
    this.loading = true
    this.today = this.getNowFormatDate()
    this.getDateRange()
    this.getProcessDetailsWorkshop()
    this.getEquipmentOperationStatusStatistics()
    // this.getProcessDetailsLabor()
    // this.getProcessDetails()
    // this.getProcessDetailsConsumptionDay()
    // this.getProcessDetailsConsumptionMonth()
  },
  mounted() {
    this.$nextTick(() => {
      let top = document.body.clientHeight
      let innerTop = document.querySelector('#CushaSvg').offsetHeight
      this.scrollY = top - innerTop - 66 - 48 - 35 - 40 - 36
      this.scrollY1 = top - 66 - 48 - 35 - 56
      this.scrollY2 = top - 120 - 36
    })
  },
  filters: {
    dateFormate(val) {
      return moment(val).format('MM/DD')
    }
  },
  methods: {
    changeTab() {
      switch (this.tableToggle) {
        case '车间':
          this.getProcessDetailsWorkshop()
          break
        case '用工':
          this.getProcessDetailsLabor()
          this.getProcessDetailsLaborEachDevice()
          break
        case '明细':
          this.getProcessDetails()
          break
        default:
          this.getProcessDetailsWorkshop()
          break
      }
    },
    // 车间
    getProcessDetailsWorkshop() {
      this.loading = true
      getAction(this.url.processDetailsWorkshop, {
        company: this.$store.state.company,
        workshop: this.$store.state.workshopNo,
        workingProcedure: 5,
        productCategory: 2,
        planTime: new Date().toISOString().slice(0, 10)
      }).then(res => {
        this.tableData = res.result
        this.loading = false
      })
    },
    getEquipmentOperationStatusStatistics() {
      getAction(this.url.equipmentOperationStatusStatistics, {
        company: this.$store.state.company,
        workshop: this.$store.state.workshopNo,
        workingProcedure: 5,
        productCategory: 2
      }).then(res => {
        this.status.forEach(item => {
          switch (item.label) {
            case '运行':
              item.data = res.result.running
              break
            case '停止':
              item.data = res.result.stop
              break
            case '故障':
              item.data = res.result.fault
              break
            case '满纱满桶':
              item.data = res.result.fullOfYarnAndBarrels
              break
            case '通讯失败/停电':
              item.data = res.result.communicationFailure
              break
            case '计划停台':
              item.data = res.result.planStop
              break
            default:
              item.data = 0
          }
        })
      })
    },
    getProcessDetailsLabor() {
      this.loading1 = true
      getAction(this.url.processDetailsLabor, {
        company: this.$store.state.company,
        workshop: this.$store.state.workshopNo,
        workingProcedure: 5,
        productCategory: 2,
        pageNo: 1,
        pageSize: -1,
        planTime: new Date().toISOString().slice(0, 10)
      }).then(res => {
        console.log('restableData1', res)
        this.tableData1 = res.result.records
        this.loading1 = false
      })
    },
    getProcessDetailsLaborEachDevice() {
      this.loading3 = true
      getAction(this.url.processDetailsLaborEachDevice, {
        company: this.$store.state.company,
        workshop: this.$store.state.workshopNo,
        workingProcedure: 5,
        productCategory: 2,
        pageNo: 1,
        pageSize: -1,
        planTime: new Date().toISOString().slice(0, 10)
      }).then(res => {
        console.log('restableData3', res)
        this.tableData3 = res.result.records
        this.loading3 = false
      })
    },
    getProcessDetails() {
      this.loading2 = true
      getAction(this.url.processDetails, {
        company: this.$store.state.company,
        workshop: this.$store.state.workshopNo,
        workingProcedure: 5,
        productCategory: 2,
        pageSize: -1
      }).then(res => {
        console.log('restableData2', res)
        this.tableData2 = res.result.records
        this.loading2 = false
      })
    },
    // getProcessDetailsConsumptionDay() {
    //   getAction(this.url.processDetailsConsumptionDay, {
    //     company: this.$store.state.company,
    //     workshop: this.$store.state.workshopNo,
    //     productCategory: 2,
    //     planTime: new Date().toISOString().slice(0, 10)
    //   }).then(res => {
    //     console.log('restableData3', res)
    //     this.tableData3 = res.result.records
    //     this.loading3 = false
    //   })
    // },
    // getProcessDetailsConsumptionMonth() {
    //   getAction(this.url.processDetailsConsumptionMonth, {
    //     company: this.$store.state.company,
    //     workshop: this.$store.state.workshopNo,
    //     productCategory: 2,
    //     planTime: new Date().toISOString().slice(0, 10)
    //   }).then(res => {
    //     console.log('restableData4', res)
    //     this.tableData4 = res.result.records
    //     this.loading4 = false
    //   })
    // },
    // 耗电日报排序
    daySortChange({ prop, order }) {
      this.riBaoFieldName = prop
      this.riBaoFieldOrder = order === 'descending' ? 'DESC' : 'ASC'
      this.getElectricityDayData(1)
    },
    // 耗电月报排序
    monthSortChange({ prop, order }) {
      this.yueBaoFieldName = prop
      this.yueBaoFieldOrder = order === 'descending' ? 'DESC' : 'ASC'
      this.getElectricityMonthData(1)
    },
    // 获取连续车台
    getSeiresDevsn(arr) {
      var result = [],
        i = 0,
        str = ''
      if (arr.length > 0) {
        result[i] = [arr[0]]
        arr.reduce(function(prev, cur) {
          parseInt(cur) - parseInt(prev) === 1 ? result[i].push(cur) : (result[++i] = [cur])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str += `${item[0]}-${item[item.length - 1]}、`
          } else {
            str += `${item[0]}、`
          }
        })
        str = str.substring(0, str.length - 1)
      } else {
        str = ''
      }
      return str
    },
    getNowFormatDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    percentFormatter(row, column, cellValue) {
      return toFixed(cellValue) + '%'
    },
    percentFloatFormatter(row, column, cellValue) {
      return toFixed(cellValue) + '%'
    },
    floatFormatter(row, column, cellValue) {
      return toFixed(cellValue)
    },
    mulFormatter(row, column, cellValue) {
      return toFixed(mul(cellValue, 0.01))
    },
    showDialog() {
      this.Dialog = true
    },
    // 重新进入1.5级弹窗轮询
    getTableData() {
      this.$EventBus.$emit('inlineDialog', 'open', 'CUSHA', { start: 1, end: 16 })
    },
    // 关闭1.5级弹窗
    closeDialog() {
      this.$parent.closeDialogTech()
    },
    // 合并表格
    mergeTable(data, index) {
      this['areaArr' + index] = []
      this['areaSpan' + index] = 0
      let areaArr = this['areaArr' + index]
      let areaSpan = this['areaSpan' + index]
      for (let i = 0; i < data.length; i++) {
        if (i == 0) {
          areaArr.push(1)
          areaSpan = 0
        } else {
          if (data[i].name == data[i - 1].name) {
            areaArr[areaSpan] += 1
            areaArr.push(0)
          } else {
            areaArr.push(1)
            areaSpan = i
          }
        }
      }
    },
    // 表格合并
    objectSpanMethod1({ rowIndex, columnIndex }) {
      // 总计行
      if (columnIndex === 0) {
        const row1 = this.areaArr1[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    // 表格合并
    objectSpanMethod2({ rowIndex, columnIndex }) {
      // 总计行
      if (columnIndex === 0) {
        const row1 = this.areaArr2[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    // 表格合并
    objectSpanMethod3({ rowIndex, columnIndex }) {
      // 总计行
      if (columnIndex === 0) {
        const row1 = this.areaArr3[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    // 表格合并
    objectSpanMethod4({ rowIndex, columnIndex }) {
      // 总计行
      if (columnIndex === 0) {
        const row1 = this.areaArr4[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    sortChange(tableindex) {
      let data = this.$refs['table' + tableindex].tableData
      this.mergeTable(data, tableindex)
    },
    clearSort(ref) {
      if (this.$refs[ref]) {
        this.$refs[ref].clearSort()
      }
    },
    toggleWorker(val) {
      this.worker = val
    },
    openEnlargeDialog() {
      this.enlargeDialog = true
    },

    // 导出表格
    exportxls(type, startTime, endTime) {
      if (type == '日报') {
        startTime = moment().format('YYYY-MM-DD 00:00:00')
        endTime = moment().format('YYYY-MM-DD 23:59:59')
      }

      if (type == '月报') {
        startTime = this.yueBaoDate.startTime
        endTime = this.yueBaoDate.endTime
      }

      const params = {
        cj: type == '月报' ? this.cjVal : this.workshopName,
        startTime: startTime,
        endTime: endTime,
        gx: '粗纱',
        org: '立华'
      }
      const url = urlConfig.exportXLs
      request
        .post2(url, params)
        .then(res => {
          const data = res && res.data
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), '报表.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '报表.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
        .catch(err => {})
    },

    // 报表请求
    getChartData(params) {
      const url = urlConfig.queryChart
      params = { org: '立华', gx: '粗纱', pageNo: 1, pageSize: 10, ...params }
      return new Promise((resolve, reject) => {
        request
          .post(url, params)
          .then(res => {
            if (res.data.code == 1) {
              resolve(res.data)
            } else {
              this.$message.error('请求失败')
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 获取日报数据
    getRiBaoData(currentPage) {
      this.RiBaoData.loading = true
      this.$forceUpdate()
      this.getChartData({
        cj: this.workshopName,
        startTime: moment().format('YYYY-MM-DD 00:00:00'),
        endTime: moment().format('YYYY-MM-DD 23:59:59'),
        pageNo: currentPage
      }).then(res => {
        this.RiBaoData = {
          loading: false,
          current: res.data.current,
          total: res.data.total,
          size: res.data.size,
          tableData: res.data.records,
          efficiencyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].efficiencyActual : '') : '',
          energyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].energyActual : '') : '',
          yieldActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].yieldActual : '') : ''
        }
        this.$forceUpdate()
      })
    },
    // 日报换页
    handleRiBaoCurrentChange(val) {
      this.getRiBaoData(val)
    },

    // 获取周报数据
    getZhouBaoData(currentPage, startTime, endTime) {
      const key = moment(startTime).format('YYYY-MM-DD')

      this.$set(this.ZhouBaoData[key], 'loading', true)
      this.$forceUpdate()

      this.getChartData({
        cj: this.workshopName,
        startTime: startTime,
        endTime: endTime,
        pageNo: currentPage
      }).then(res => {
        this.ZhouBaoData[key] = {
          startTime: startTime,
          endTime: endTime,
          loading: false,
          current: res.data.current,
          total: res.data.total,
          size: res.data.size,
          tableData: res.data.records,
          efficiencyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].efficiencyActual : '') : '',
          energyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].energyActual : '') : '',
          yieldActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].yieldActual : '') : ''
        }
        this.$set(this.ZhouBaoData[key], 'loading', false)
        this.$forceUpdate()
      })
    },
    // 周报日期
    getDateRange() {
      let dateGroup = []
      let firstTempNum =
        7 -
        moment()
          .startOf('month')
          .isoWeekday()
      let tempDate = moment().startOf('month')
      const currentDate = moment().date()

      if (currentDate > firstTempNum + 1) {
        dateGroup.push({
          firstDay: moment()
            .startOf('month')
            .format('YYYY-MM-DD 00:00:00'),
          endDay: tempDate.add(firstTempNum, 'days').format('YYYY-MM-DD 23:59:59')
        })

        while (currentDate >= tempDate.date() + 7) {
          dateGroup.push({
            firstDay: tempDate.add(1, 'days').format('YYYY-MM-DD 00:00:00'),
            endDay: tempDate.add(6, 'days').format('YYYY-MM-DD 23:59:59')
          })
        }

        if (currentDate > tempDate.date()) {
          dateGroup.push({
            firstDay: tempDate.add(1, 'days').format('YYYY-MM-DD 00:00:00'),
            endDay: moment().format('YYYY-MM-DD 23:59:59')
          })
        }
      } else {
        dateGroup.push({
          firstDay: moment()
            .startOf('month')
            .format('YYYY-MM-DD 00:00:00'),
          endDay: moment().format('YYYY-MM-DD 23:59:59')
        })
      }
      this.zhouBaoDate = dateGroup
      dateGroup.map(item => {
        this.ZhouBaoData[moment(item.firstDay).format('YYYY-MM-DD')] = {
          loading: false,
          startTime: item['firstDay'],
          endTime: item['endDay']
        }
      })
    },
    // 周报换页
    handleZhouBaoCurrentChange(val, index) {
      const startTime = this.ZhouBaoData[index].startTime
      const endTime = this.ZhouBaoData[index].endTime
      this.getZhouBaoData(val, startTime, endTime)
    },

    // 获取月报数据
    getYueBaoData(currentPage) {
      this.YueBaoData.loading = true
      this.$forceUpdate()
      this.getChartData({
        cj: this.cjVal,
        startTime: this.yueBaoDate.startTime,
        endTime: this.yueBaoDate.endTime,
        pageNo: currentPage
      }).then(res => {
        this.YueBaoData = {
          loading: false,
          current: res.data.current,
          total: res.data.total,
          size: res.data.size,
          tableData: res.data.records,
          efficiencyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].efficiencyActual : '') : '',
          energyActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].energyActual : '') : '',
          yieldActual: res.data2.length > 0 ? (res.data2[0] ? res.data2[0].yieldActual : '') : ''
        }
        this.$forceUpdate()
      })
    },
    // 获取车间
    getCJ() {
      const params = {
        dic_bh: 'workshop'
      }
      const url = urlConfig.queryCJ
      request
        .post1(url, params)
        .then(res => {
          this.cjList = res.data.data.dataList
        })
        .catch(err => {})
    },
    // 月报换页
    handleYueBaoCurrentChange(val) {
      this.getYueBaoData(val)
    },
    // 月报日期选择
    handleYueBaoDateChange(val) {
      this.yueBaoDate = {
        startTime: moment(val)
          .startOf('month')
          .format('YYYY-MM-DD 00:00:00'),
        endTime: moment(val)
          .endOf('month')
          .format('YYYY-MM-DD 23:59:59')
      }
      this.getYueBaoData(1)
    },
    // 月报车间选择
    handleDropDown(val) {
      this.cjVal = val
      this.getYueBaoData(1)
    },

    // 耗电日报表请求
    getElectricityChartData(params) {
      return new Promise((resolve, reject) => {
        getAction(this.url.processDetailsConsumptionDay, {
          company: this.$store.state.company,
          workshop: this.$store.state.workshopNo,
          workingProcedure: 5,
          productCategory: 2,
          pageNo: 1,
          pageSize: 10,
          ...params
        })
          .then(res => {
            if (res.code == 200) {
              resolve(res)
            } else {
              this.$message.error('请求失败')
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 耗电报表请求月报
    getElectricityMonthChartData(params) {
      return new Promise((resolve, reject) => {
        getAction(this.url.processDetailsConsumptionMonth, {
          company: this.$store.state.company,
          workshop: this.$store.state.workshopNo,
          workingProcedure: 5,
          productCategory: 2,
          pageNo: 1,
          pageSize: 10,
          ...params
        })
          .then(res => {
            if (res.code == 200) {
              resolve(res)
            } else {
              this.$message.error('请求失败')
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 耗电导出表格
    electricityExportXls(type, startTime, endTime, pageNo = 1, pageSize = 20) {
      let url = ''
      let fieldName = ''
      let fieldOrder = ''
      if (type == '耗电日报') {
        startTime = this.electricityDayDate.startTime
        endTime = this.electricityDayDate.endTime
        pageNo = this.electricityDayData.current
        pageSize = this.electricityDayData.size
        url = urlConfig.electricityExportXLs
        fieldName = this.riBaoFieldName
        fieldOrder = this.riBaoFieldOrder
      }

      if (type == '耗电月报') {
        startTime = this.electricityMonthDate.startTime
        endTime = this.electricityMonthDate.endTime
        pageNo = this.electricityMonthData.current
        pageSize = this.electricityMonthData.size
        url = urlConfig.electricityMonthExportXLs
        fieldName = this.yueBaoFieldName
        fieldOrder = this.yueBaoFieldOrder
      }

      const params = {
        startTime: startTime,
        endTime: endTime,
        pageNo: pageNo,
        pageSize: pageSize,
        productCategory: '粗纱',
        workshop: this.cjVal,
        fieldName,
        fieldOrder
      }

      request
        .post2(url, params)
        .then(res => {
          const data = res && res.data
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(
              new Blob([data], { type: 'application/vnd.ms-excel' }),
              '粗纱' + type + '报表.xls'
            )
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '粗纱' + type + '报表.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
        .catch(err => {})
    },
    // 耗电日报翻页
    handleDayCurrentChange(val) {
      this.getElectricityDayData(val)
    },
    handleDaySizeChange(pageSize) {
      this.getElectricityDayData(1, pageSize)
    },
    // 耗电月报翻页
    handleMonthCurrentChange(val) {
      this.getElectricityMonthData(val)
    },
    handleMonthSizeChange(pageSize) {
      this.getElectricityMonthData(1, pageSize)
    },
    // 耗电日报日期选择
    handleElectricityDayDateChange(val) {
      this.electricityDayDate = {
        planTime: moment(val)
          .startOf('day')
          .format('YYYY-MM-DD')
      }
      this.getElectricityDayData(1)
    },
    // 获取耗电日报数据
    getElectricityDayData(currentPage = 1, pageSize = 20) {
      this.electricityDayData.loading = true
      this.getElectricityChartData({
        planTime: this.electricityDayDate.planTime,
        pageNo: currentPage,
        pageSize: -1
        // fieldName: this.riBaoFieldName,
        // fieldOrder: this.riBaoFieldOrder
      }).then(res => {
        // if (!res.result.records) {
        // console.log(2132132130098090)
        // this.electricityDayData.loading = false
        //   this.electricityDayData.tableData = []
        //   return
        // }
        // 处理数据统计
        // let listData = this.resetData(res.records)
        this.electricityDayData = {
          loading: false,
          current: res.result.current,
          total: res.result.total,
          size: res.result.size,
          tableData: res.result.records
        }
        this.$forceUpdate()
      })
    },
    // 耗电月报日期选择
    handleElectricityMonthDateChange(val) {
      this.electricityMonthDate = {
        planTime: moment(val)
          .startOf('month')
          .format('YYYY-MM')
      }
      this.getElectricityMonthData(1)
    },
    // 获取耗电月报数据
    getElectricityMonthData(currentPage = 1, pageSize = 20) {
      this.electricityMonthData.loading = true
      this.$forceUpdate()
      this.getElectricityMonthChartData({
        workshop: this.workshopNo,
        planTime: this.electricityMonthDate.planTime + '-01',
        pageNo: currentPage,
        pageSize: -1
        // fieldName: this.yueBaoFieldName,
        // fieldOrder: this.yueBaoFieldOrder
      }).then(res => {
        // 处理数据统计
        // if (!res.records) {
        //   this.electricityMonthData.loading = false
        //   this.electricityMonthData.tableData = []
        //   return
        // }
        // let listData = this.resetData(res.records)
        this.electricityMonthData = {
          loading: false,
          current: res.result.current,
          total: res.result.total,
          size: res.result.size,
          tableData: res.result.records
        }
        this.$forceUpdate()
      })
    },
    resetData(listData = []) {
      let newListData = []
      if (listData.length > 0) {
        let pz = listData[0].pz
        let outPut = 0
        let consumption = 0
        let outConsumption = 0
        let production = 0
        let deviceNoStart = listData[0].deviceNo
        for (let i = 0; i < listData.length; i++) {
          if (listData[i].pz === pz) {
            newListData.push(listData[i])
            outPut += listData[i].outPut
            consumption += listData[i].consumption
            outConsumption += listData[i].outConsumption
            production += listData[i].production
            // 判断是否是最后一条
            if (i === listData.length - 1) {
              newListData.push({
                ...listData[i],
                time: '合计',
                outPut: outPut.toFixed(4),
                consumption: consumption,
                outConsumption: outConsumption.toFixed(4),
                production: production.toFixed(4),
                deviceNo: deviceNoStart + '-' + listData[i].deviceNo
              })
            }
          } else {
            pz = listData[i].pz
            newListData.push({
              ...listData[i - 1],
              time: '合计',
              outPut: outPut.toFixed(4),
              consumption: consumption,
              outConsumption: outConsumption.toFixed(4),
              production: production.toFixed(4),
              deviceNo: deviceNoStart + '-' + listData[i - 1].deviceNo
            })
            outPut = 0
            consumption = 0
            outConsumption = 0
            production = 0
            deviceNoStart = listData[i].deviceNo
            newListData.push(listData[i])
          }
        }
      }
      return newListData
    }
  }
}
</script>

<style lang="less">
@import '~@/assets/less/workshop.less';
.tech-dialog-cusha .ant-modal {
  height: 100vh;
  border: 3px solid #52abb1;
  margin: 0 auto;

  .el-dialog__headerbtn {
    top: 3%;
  }

  .header {
    height: 66px;
    background-size: contain;
    background-position-x: center;
    position: relative;

    .today {
      display: flex;
      align-items: center;
      position: absolute;
      top: 25px;
      left: 28px;

      span {
        margin-left: 10px;
        font-size: 16px;
        font-weight: 600;
        color: black;
      }
    }
  }

  .main {
    display: flex;
    justify-content: space-between;

    .legend .xiaolv {
      width: 300px;
      height: 20px;
      background: url('~@/assets/img/status/legend.png') no-repeat;
      background-size: cover;
      margin-left: 50px;
    }

    .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
      box-shadow: none;
    }
  }

  .content {
    height: calc((100vh - 136px) * 0.6);
    margin-bottom: 20px;
    display: flex;
    justify-content: center;

    .cusha .cusha-inline {
      display: flex;
      flex-direction: column-reverse;
      height: 100%;
      justify-content: space-around;

      position: relative;
      margin-top: 20px;

      .cusha_item {
        transform: scale(1.8);
      }

      .cusha_row {
        margin-top: 346px;
      }

      .dongli:first-child {
        position: absolute;
        left: -40px;
      }

      .dongli1 {
        position: absolute;
        bottom: 20px;
      }
      .dongli2 {
        position: absolute;
        top: 16px;
      }
      .img {
        width: 20px;
        height: 10px;
      }
    }
  }

  // element cover style
  .el-dialog__header {
    padding: 0 20px 0 20px;
  }

  .el-dialog__body {
    height: calc(100% - 66px);
    padding: 24px 48px;
    box-sizing: border-box;
  }

  .el-radio-button__inner {
    width: 90px;
    height: 35px;
    padding: 0;
    text-align: center;
    line-height: 35px;
    font-size: 16px;
    color: #fff;
    margin-right: 2px;
    background: rgba(38, 146, 156, 0.4);
    border-radius: 4px 4px 0 0 !important;
    border: 1px solid rgba(38, 146, 156, 0.4);
  }

  .el-radio-button:first-child .el-radio-button__inner {
    border-left: none;
  }

  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background: #26929c;
    border: 1px solid #69d7fb;
  }

  .el-table {
    overflow-y: hidden;
  }
}
</style>
